package com.ruoyi.project.bajiaostar.user;


import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.framework.aop.NoRepeatSubmit;
import com.ruoyi.framework.aop.UserRepeatSubmit;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.bajiaostar.tGoodDetail.service.ITGoodDetailService;
import com.ruoyi.project.bajiaostar.tGoodOrder.domain.TGoodOrder;
import com.ruoyi.project.bajiaostar.tGoodOrder.service.ITGoodOrderService;
import com.ruoyi.project.bajiaostar.tOrderStayRecord.domain.TOrderStayRecord;
import com.ruoyi.project.bajiaostar.tOrderStayRecord.service.ITOrderStayRecordService;
import com.ruoyi.project.bajiaostar.user.dto.*;
import com.ruoyi.project.user.domain.TUser;
import com.ruoyi.project.user.service.ITUserService;
import com.ruoyi.project.utils.RedisUtils;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;

/**
 * 商品下单
 */
@RestController
@RequestMapping("/nt/goodOrder")
@Slf4j
public class WebGoodOrderController extends BaseController {

    @Autowired
    ITGoodDetailService goodDetailService;
    @Autowired
    ITGoodOrderService goodOrderService;
    @Autowired
    ITUserService userService;
    @Autowired
    RedisUtils redisUtils;
    @Autowired
    ITOrderStayRecordService orderStayRecordService;


    @ApiOperation("下单")
    @Log(title = "APP接口管理", businessType = BusinessType.OTHER)
    @PostMapping("/addGoodOrder")
    @NoRepeatSubmit
    public AjaxResult addGoodOrder(@RequestBody AddGoodOrderDto req) {
        try {
            if (ObjectUtils.isEmpty(req)) {
                return AjaxResult.error("信息有误,请检查");
            }
            req.setUserId(getAppUserId());
            return goodOrderService.addGoodOrder(req);
        } catch (Exception e) {
            return this.error("下单失败 " + e.getMessage());
        }
    }

    @ApiOperation("修改下单地址")
    @Log(title = "APP接口管理", businessType = BusinessType.OTHER)
    @PostMapping("/updateGoodOrderForAddress")
    @NoRepeatSubmit
    public AjaxResult updateGoodOrderForAddress(@RequestBody UpdateGoodOrderForAddressDto req) {
        try {
            if (ObjectUtils.isEmpty(req)) {
                return AjaxResult.error("信息有误,请检查");
            }
            return goodOrderService.updateGoodOrderForAddress(req.getOrderId(), req.getAddress(), req.getRecipientsName(), req.getRecipientsPhone(), req.getSomeRemark(), req.getUserRemark());
        } catch (Exception e) {
            return this.error("修改下单地址失败 " + e.getMessage());
        }
    }

    @ApiOperation("修改订单状态")
    @Log(title = "APP接口管理", businessType = BusinessType.OTHER)
    @PostMapping("/updateGoodOrderForStatus")
    @NoRepeatSubmit
    public AjaxResult updateGoodOrderForStatus(@RequestBody UpdateGoodOrderForStatusDto req) {
        try {
            if (ObjectUtils.isEmpty(req)) {
                return AjaxResult.error("信息有误,请检查");
            }
            boolean b = redisUtils.setLock("order:lock:" + req.getOrderId(), 3);
            if (!b) {
                return AjaxResult.error("亲，不要太着急，请稍后再试");
            }
            return goodOrderService.updateGoodOrderForStatus(req.getOrderId(), req.getOrderStatus(), req.getCancelType());
        } catch (Exception e) {
            return this.error("修改订单状态失败 " + e.getMessage());
        }
    }

    @ApiOperation("订单一键发货")
    @Log(title = "APP接口管理", businessType = BusinessType.OTHER)
    @PostMapping("/updateOneClickShipping")
    @NoRepeatSubmit
    public AjaxResult updateOneClickShipping(@RequestBody UpdateOneClickShippingDto dto) {
        try {
            boolean b = redisUtils.setLock("order:lock:order001", 3);
            if (!b) {
                return AjaxResult.error("亲，不要太着急，请稍后再试");
            }
            if(ObjectUtils.isEmpty(dto) || ObjectUtils.isEmpty(dto.getOrderIds())){
                return AjaxResult.error("请选择发货订单号");
            }
            for (Long orderId:dto.getOrderIds()) {
                try {
                    goodOrderService.updateGoodOrderForStatus(orderId, 2,null);
                } catch (Exception e) {
                    log.error("订单一键发货-》订单异常,订单为：{},异常信息:", orderId, e.getMessage());
                }
            }
            /*TGoodOrder order = new TGoodOrder();
            order.setOrderStatus(1);
            List<TGoodOrder> list = goodOrderService.selectTGoodOrderList(order);
            if (!ObjectUtils.isEmpty(list)) {
                for (TGoodOrder goodOrder : list) {
                    try {
                        goodOrderService.updateGoodOrderForStatus(goodOrder.getId(), 2, null);
                    } catch (Exception e) {
                        log.error("订单一键发货-》订单异常,订单为：{},异常信息:", goodOrder.getId(), e.getMessage());
                    }
                }
            }*/

            return AjaxResult.success();
        } catch (Exception e) {
            return this.error("订单一键发货失败 " + e.getMessage());
        }
    }


    @ApiOperation("订单数据回滚")
    @Log(title = "APP接口管理", businessType = BusinessType.OTHER)
    @PostMapping("/updateGoodOrderStatus")
    @NoRepeatSubmit
    public AjaxResult updateGoodOrderStatus() {
        try {
            boolean b = redisUtils.setLock("order:lock:order002", 10);
            if (!b) {
                return AjaxResult.error("亲，不要太着急，请稍后再试");
            }
            Integer in[] = {484, 483, 482, 481, 479, 478, 476, 475, 473, 471, 470, 469, 468, 466, 464, 461, 460, 459, 458, 456, 455, 453, 452, 451, 450, 449, 448, 447, 446, 445, 442, 441, 440, 439, 438, 437, 436, 435, 434, 433, 432, 430, 429, 428, 427, 426, 425, 422, 421, 420, 419, 417, 416, 414, 413, 412, 411, 410, 409, 408, 407, 405, 403, 401, 394, 393, 392, 391, 389, 387, 384, 383, 379, 375, 373, 362, 360, 354, 353, 352, 349, 344, 341, 335, 333, 325, 321, 319, 314, 313, 312, 311, 310, 309, 308, 306, 305, 303, 301, 296, 294, 293, 292, 291, 290, 289, 288, 286, 285, 282, 281, 279, 278, 277, 274, 272, 271, 270, 269, 268, 267, 266, 265, 261, 258, 257, 256, 255, 254, 252, 251, 248, 247, 246, 241, 240, 235, 233, 232, 231, 230, 229, 228, 227, 223, 214, 212, 209, 206, 204, 202, 199, 197, 196, 193, 192, 191, 190, 187, 181, 180, 177, 175};
            for (int i = 1; i <= in.length; i++) {
                try {
                    goodOrderService.updateGoodOrderStatus(Long.parseLong(in[i]+""));
                } catch (Exception e) {
                    log.error("订单数据回滚-》订单异常,订单为：{},异常信息:{}", in[i], e.getMessage());
                }
            }
            return AjaxResult.success();
        } catch (Exception e) {
            return this.error("订单数据回滚失败 " + e.getMessage());
        }
    }

    @ApiOperation("查询用户订单")
    @Log(title = "APP接口管理", businessType = BusinessType.OTHER)
    @PostMapping("/findUserGoodOrder")
    public TableDataInfo findUserGoodOrder(@RequestBody FindUserGoodOrderDto dto) {
        try {
            Long appUserId = getAppUserId();
            startPage(dto.getPageNum(), dto.getPageSize());
            TGoodOrder order = new TGoodOrder();
            order.setUserId(appUserId);
            order.setOrderStatus(dto.getOrderStatus());
           /* if (!ObjectUtils.isEmpty(dto.getOrderStatus()) && dto.getOrderStatus().equals(2)) {
                order.setFindType(1);
            }*/
            if(!ObjectUtils.isEmpty(dto.getDateType())){
                if(dto.getDateType().equals(1)){
                    order.setStartTime(DateUtils.getBeginDate(DateUtils.addDayTime(new Date(),-7)));
                }else if(dto.getDateType().equals(2)){
                    order.setStartTime(DateUtils.getBeginDate(DateUtils.addDayTime(new Date(),-30)));
                }else if(dto.getDateType().equals(3)){
                    order.setStartTime(DateUtils.getBeginDate(DateUtils.addDayTime(new Date(),-90)));
                }
                order.setEndTime(DateUtils.getEndDate(new Date()));
            }
            order.setGoodId(dto.getGoodId());
            order.setGoodName(dto.getGoodName());
            List<TGoodOrder> list = goodOrderService.selectTGoodOrderUserList(order);
            if(!ObjectUtils.isEmpty(list)){
                for (TGoodOrder order1:list){
                    order1.setOrderCountPrice(order1.getPrice()*order1.getBuyNum());
                    if(!ObjectUtils.isEmpty(order1.getUserIdentity())){
                        if (order1.getUserIdentity().equals(0)) {
                            order1.setUserPrice(order1.getDefaultSettlementCountPrice());
                        } else if (order1.getUserIdentity().equals(1)) {
                            order1.setUserPrice(order1.getMemberSettlementCountPrice());
                        } else if (order1.getUserIdentity().equals(2)) {
                            order1.setUserPrice(order1.getTwoMemberSettlementCountPrice());
                        }
                    }
                    long subtract = DateUtils.subtract(order1.getOverdueDete(), new Date());
                    if (subtract < 1) {
                        subtract = 0L;
                    }
                    order1.setSurplusDate(subtract);
                    if (order1.getUserStayPayPrice() < 1) {
                        order1.setStayPayCountPrice(order1.getOrderCountPrice() - order1.getUserPrice());
                    } else {
                        order1.setStayPayCountPrice(order1.getUserStayPayPrice());
                    }
                }
            }
            return getDataTable(list);
        } catch (Exception e) {
            log.error("查询用户订单状态失败 " + e.getMessage());
            throw new RuntimeException("查询失败");
        }
    }


    @ApiOperation("查询管理员订单")
    @Log(title = "APP接口管理", businessType = BusinessType.OTHER)
    @PostMapping("/findAdminGoodOrder")
    public TableDataInfo findAdminGoodOrder(@RequestBody FindUserGoodOrderDto dto) {
        try {
            startPage(dto.getPageNum(), dto.getPageSize());
            TGoodOrder order = new TGoodOrder();
            order.setOrderStatus(dto.getOrderStatus());
            order.setGoodName(dto.getGoodName());
            if(!ObjectUtils.isEmpty(dto.getDateType())){
                if(dto.getDateType().equals(1)){
                    order.setStartTime(DateUtils.getBeginDate(DateUtils.addDayTime(new Date(),-7)));
                }else if(dto.getDateType().equals(2)){
                    order.setStartTime(DateUtils.getBeginDate(DateUtils.addDayTime(new Date(),-30)));
                }else if(dto.getDateType().equals(3)){
                    order.setStartTime(DateUtils.getBeginDate(DateUtils.addDayTime(new Date(),-90)));
                }
                order.setEndTime(DateUtils.getEndDate(new Date()));
            }
            order.setGoodId(dto.getGoodId());
            List<TGoodOrder> list = goodOrderService.selectTGoodOrderList(order);
            if (!ObjectUtils.isEmpty(list)) {
                for (TGoodOrder order1 : list) {
                    order1.setOrderCountPrice(order1.getPrice() * order1.getBuyNum());
                    //查找用户
                    TUser user = userService.selectTUserById(order1.getUserId());
                    if (!ObjectUtils.isEmpty(user)) {
                        order1.setUserName(user.getUserName());
                        order1.setOrderUserRemark(user.getUserRemark());
                    }
                    if (!ObjectUtils.isEmpty(order1.getUserIdentity())) {
                        if (order1.getUserIdentity().equals(0)) {
                            order1.setUserPrice(order1.getDefaultSettlementCountPrice());
                        } else if (order1.getUserIdentity().equals(1)) {
                            order1.setUserPrice(order1.getMemberSettlementCountPrice());
                        } else if (order1.getUserIdentity().equals(2)) {
                            order1.setUserPrice(order1.getTwoMemberSettlementCountPrice());
                        }
                    }
                    long subtract = DateUtils.subtract(order1.getOverdueDete(), new Date());
                    if (subtract < 1) {
                        subtract = 0L;
                    }
                    order1.setSurplusDate(subtract);
                    if (order1.getUserStayPayPrice() < 1) {
                        order1.setStayPayCountPrice(order1.getOrderCountPrice() - order1.getUserPrice());
                    } else {
                        order1.setStayPayCountPrice(order1.getUserStayPayPrice());
                    }
                }
            }
            return getDataTable(list);
        } catch (Exception e) {
            log.error("查询用户订单状态失败 " + e.getMessage());
            throw new RuntimeException("查询失败");
        }
    }

    @ApiOperation("修改订单待结算金额")
    @Log(title = "APP接口管理", businessType = BusinessType.OTHER)
    @PostMapping("/updateUserStayPayPrice")
    @NoRepeatSubmit
    public AjaxResult updateUserStayPayPrice(@RequestBody UpdateUserStayPayPriceDto dto) {
        try {
            boolean b = redisUtils.setLock("order:lock:updateUserStayPayPrice" + dto.getOrderId(), 3);
            if (!b) {
                return AjaxResult.error("亲，不要太着急，请稍后再试");
            }
            return goodOrderService.updateUserStayPayPrice(dto.getOrderId(), dto.getUserStayPayPrice());
        } catch (Exception e) {
            return this.error("修改订单待结算金额失败 " + e.getMessage());
        }
    }

    @ApiOperation("查询待结算变更记录列表")
    @Log(title = "APP接口管理", businessType = BusinessType.OTHER)
    @PostMapping("/findOrderStayPayRecord")
    @NoRepeatSubmit
    public TableDataInfo findOrderStayPayRecord(@RequestBody FindOrderStayPayRecordDto dto) {
        try {
            if (ObjectUtils.isEmpty(dto) || ObjectUtils.isEmpty(dto.getOrderId())) {
                throw new RuntimeException("参数有误");
            }
            startPage(dto.getPageNum(), dto.getPageSize());
            TOrderStayRecord record = new TOrderStayRecord();
            record.setOrderId(dto.getOrderId());
            List<TOrderStayRecord> records = orderStayRecordService.selectTOrderStayRecordList(record);
            return getDataTable(records);
        } catch (Exception e) {
            throw new RuntimeException("查询待结算变更记录失败");
        }
    }


    @ApiOperation("发送当日邮件(管理员)")
    @Log(title = "APP接口管理", businessType = BusinessType.OTHER)
    @PostMapping("/execueOrderMailDeteAdminTask")
    @UserRepeatSubmit
    public AjaxResult execueOrderMailDeteAdminTask() {
        try {
            return goodOrderService.execueOrderMailDeteAdminTask();
        } catch (Exception e) {
            throw new RuntimeException("发送当日邮件(管理员)异常");
        }
    }


    @ApiOperation("根据商品id获取所有未发货订单信息 ")
    @Log(title = "APP接口管理", businessType = BusinessType.OTHER)
    @PostMapping("/findStayOrder")
    @NoRepeatSubmit
    public AjaxResult findStayOrder(@RequestBody FindStayOrderDto dto ) {
        try {
            return goodOrderService.findStayOrder(dto.getGoodId());
        } catch (Exception e) {
            return this.error("订单一键发货失败 " + e.getMessage());
        }
    }
    @ApiOperation("根据用户id查询下单商品名称 ")
    @Log(title = "APP接口管理", businessType = BusinessType.OTHER)
    @PostMapping("/findStayOrderByUserId")
    @NoRepeatSubmit
    public AjaxResult findStayOrderByUserId() {
        try {
            return goodOrderService.findStayOrderByUserId(getAppUserId());
        } catch (Exception e) {
            return this.error("根据用户id查询下单商品名称失败 " + e.getMessage());
        }
    }
}
